package com.android.JiYclock;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import com.android.JiYclock.expand.MyCount;
import com.android.JiYclock.expand.SectionedAdapter;
import com.android.JiYclock.shareAlarm.SmsService;
import com.android.JiYclock.shareAlarm.getContactList;
import com.android.JiYclocks.SpecialAlarm;
import com.android.JiYclocks.SpecialAlarms;
import com.android.JiYclocks.SpecialSetAlarm;
import com.android.jiYsoundrecorder.SoundRecorder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

/**
 *
 */
public class AlarmClock extends Activity implements OnItemClickListener {

    public static final String PREFERENCES = "AlarmClock";

    /** This must be false for production.  If true, turns on logging,
        test code, etc. */
    public static final boolean DEBUG = false;

    private SharedPreferences mPrefs;
    private LayoutInflater mFactory;
    private ListView mAlarmsList;
    private ListView mSpecialAlarmsList;
    private View addAlarm;
    private View NormalButton;
    private View ButtonSpecial;
    private Cursor NormalCursor;
    private Cursor SpecialCursor;
    private TextView day;
    private TextView hour;
    private TextView minute;
    //用户作为一个记录ListView的临时文件
    private View tempview;
    private AlarmTimeAdapter adapter ;;
    private SpecialAlarmTimeAdapter specialadapter;
    private ProgressDialog myDialog = null;
   
    private void updateIndicatorAndAlarm(boolean enabled, ImageView bar,
            Alarm alarm) {
        bar.setImageResource(enabled ? R.drawable.ic_indicator_on
                : R.drawable.ic_indicator_off);

        Alarms.enableAlarm(this, alarm.id, enabled);
        if (enabled) {
            SetAlarm.popAlarmSetToast(this, alarm.hour, alarm.minutes, alarm.daysOfWeek);
        }
    }
    
    private void updateIndicatorAndAlarm(boolean enabled, ImageView bar,
            SpecialAlarm specialalarm) {
        bar.setImageResource(enabled ? R.drawable.ic_indicator_on
                : R.drawable.ic_indicator_off);

        SpecialAlarms.enableAlarm(this, specialalarm.id, enabled);
        if (enabled) {
        	//下一步就是要更改SpecialAlarm里面的PopAlarmSetToast
         //  SpecialSetAlarm.popAlarmSetToast(this, alarm.hour, alarm.minutes, alarm.daysOfWeek);
        }
    }
    

    
    //针对从Alarm表中读取的数据进行处理
    private class AlarmTimeAdapter extends CursorAdapter {

    	private Context context;
    	
        public AlarmTimeAdapter(Context context, Cursor cursor) {
            super(context, cursor);
        }

        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View ret = mFactory.inflate(R.layout.alarm_time, parent, false);
            DigitalClock digitalClock = (DigitalClock) ret.findViewById(R.id.digitalClock);
            digitalClock.setLive(false);
            return ret;
        }

        public void bindView(View view, Context context, Cursor cursor) {
        	
            final Alarm alarm = new Alarm(cursor);
            
            //自定义的显示这个列的行
            
            View indicator = view.findViewById(R.id.indicator);

            // Set the initial resource for the bar image.
            final ImageView barOnOff = (ImageView) indicator.findViewById(R.id.bar_onoff);
            barOnOff.setImageResource(alarm.enabled ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);

            // Set the initial state of the clock "checkbox"
            final CheckBox clockOnOff =(CheckBox) indicator.findViewById(R.id.clock_onoff);
            clockOnOff.setChecked(alarm.enabled);


            this.context=context;
            // Clicking outside the "checkbox" should also change the state.
            indicator.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                    	myDialog = ProgressDialog.show(AlarmTimeAdapter.this.context,"通知ʾ","闹钟设置中",true);
						new Thread(){ 
							public void run(){ 
								try{ 
									sleep(800);
								}catch (Exception e){
									e.printStackTrace();
								}finally{
									
									myDialog.dismiss();
								}
							}
						}.start();
                    	try {
							Thread.sleep(1500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
                        clockOnOff.toggle();
                        updateIndicatorAndAlarm(clockOnOff.isChecked(),barOnOff, alarm);
                    }
            });

            DigitalClock digitalClock =(DigitalClock) view.findViewById(R.id.digitalClock);

            // set the alarm text
            final Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR_OF_DAY, alarm.hour);
            c.set(Calendar.MINUTE, alarm.minutes);
            digitalClock.updateTime(c);
            digitalClock.setTypeface(Typeface.DEFAULT);

            // Set the repeat text or leave it blank if it does not repeat.
            TextView daysOfWeekView = (TextView) digitalClock.findViewById(R.id.daysOfWeek);
            final String daysOfWeekStr = alarm.daysOfWeek.toString(AlarmClock.this, false);
            if (daysOfWeekStr != null && daysOfWeekStr.length() != 0) {
                daysOfWeekView.setText(daysOfWeekStr);
                daysOfWeekView.setVisibility(View.VISIBLE);
            } else {
                daysOfWeekView.setVisibility(View.GONE);
            }

            // Display the label
            TextView labelView = (TextView) view.findViewById(R.id.label);
            if (alarm.label != null && alarm.label.length() != 0) {
                labelView.setText(alarm.label);
                labelView.setVisibility(View.VISIBLE);
            } else {
                labelView.setVisibility(View.GONE);
            }
        }
    };
    //Alarm处理结束
    
    
    //针对从SpecialAlarm表中的数据进行处理
    private class SpecialAlarmTimeAdapter extends CursorAdapter {

    	private Context context;
    	
        public SpecialAlarmTimeAdapter(Context context, Cursor cursor) {
            super(context, cursor);
        }

        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View ret = mFactory.inflate(R.layout.specialalarm_time, parent, false);
            DigitalClock digitalClock = (DigitalClock) ret.findViewById(R.id.digitalClock);
            digitalClock.setLive(false);
            return ret;
        }

        public void bindView(View view, Context context, Cursor cursor) {
        	
            final SpecialAlarm alarm = new SpecialAlarm(cursor);
            
            View indicator = view.findViewById(R.id.indicator);

            // Set the initial resource for the bar image.
            final ImageView barOnOff = (ImageView) indicator.findViewById(R.id.bar_onoff);
            barOnOff.setImageResource(alarm.enabled ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);

            // Set the initial state of the clock "checkbox"
            final CheckBox clockOnOff =(CheckBox) indicator.findViewById(R.id.clock_onoff);
            clockOnOff.setChecked(alarm.enabled);


            this.context=context;
            // Clicking outside the "checkbox" should also change the state.
            indicator.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                    	myDialog = ProgressDialog.show(SpecialAlarmTimeAdapter.this.context,"通知","闹钟设置中.....",true);
						new Thread(){ 
							public void run(){ 
								try{ 
									sleep(1500);
								}catch (Exception e){
									e.printStackTrace();
								}finally{
									
									myDialog.dismiss();
								}
							}
						}.start();
                    	try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
                        clockOnOff.toggle();
                        updateIndicatorAndAlarm(clockOnOff.isChecked(),barOnOff, alarm);
                    }
            });

            DigitalClock digitalClock =(DigitalClock) view.findViewById(R.id.digitalClock);

            // set the alarm text
            final Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR_OF_DAY, alarm.hour);
            c.set(Calendar.MINUTE, alarm.minutes);
            digitalClock.updateTime(c);
            digitalClock.setTypeface(Typeface.DEFAULT);

            // Display the label
            TextView labelView = (TextView) view.findViewById(R.id.label);
            if (alarm.label != null && alarm.label.length() != 0) {
                labelView.setText(alarm.label);
                labelView.setVisibility(View.VISIBLE);
            } else {
                labelView.setVisibility(View.GONE);
            }
        }
    };
    
    
    @Override
    public boolean onContextItemSelected(final MenuItem item) {
    	
        final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        final int id = (int) info.id;
        View view = tempview;
         int i =  mAlarmsList.getAdapter().getItemViewType(info.position);
        Adapter alarmadapter =   ((SectionedAdapter) mAlarmsList.getAdapter()).getAdapter(0);
        Adapter specialalarmadapter =   ((SectionedAdapter) mAlarmsList.getAdapter()).getAdapter(0);
        
      final int count1= alarmadapter.getCount()+1;
      final  int count2= specialalarmadapter.getCount();
        if(i==1)
        {
        	final Cursor c = (Cursor) mAlarmsList.getAdapter().getItem(info.position);
            final Alarm alarm = new Alarm(c);
            
        	 switch (item.getItemId()) {
             case R.id.delete_alarm:
                 // Confirm that the alarm will be deleted.
                 new AlertDialog.Builder(this)
                         .setTitle(getString(R.string.delete_alarm))
                         .setMessage(getString(R.string.delete_alarm_confirm))
                         .setPositiveButton(android.R.string.ok,
                                 new DialogInterface.OnClickListener() {
                                     public void onClick(DialogInterface d, int w) {
                                         Alarms.deleteAlarm(AlarmClock.this, id);
                                         sectionadapter.notifyDataSetChanged();
                                     	
                                     }
                                 })
                         .setNegativeButton(android.R.string.cancel, null)
                         .show();
                 initCountDown();
                 return true;

             case R.id.enable_alarm:
                 
                 Alarms.enableAlarm(this, alarm.id, !alarm.enabled);
                 if (!alarm.enabled) {
                     SetAlarm.popAlarmSetToast(this, alarm.hour, alarm.minutes, alarm.daysOfWeek);
                 }
                 return true;

             case R.id.edit_alarm:
                 Intent intent = new Intent(this, SetAlarm.class);
                 intent.putExtra(Alarms.ALARM_ID, id);
                 startActivity(intent);
                 return true;
                 
                 
             case R.id.share_alarm:
            	
                // String location = Alarms.getLocationOfRecord(AlarmClock.this, alarm);
                // iintent.putExtra("Location", location);
                 Long temptime= Alarms.getMillTime(alarm);
                Alarms.SendColorMessage(AlarmClock.this, temptime, alarm.location);
                 return true;

             default:
                 break;
         }
         return super.onContextItemSelected(item);
        }else
        {
        	 final Cursor c = (Cursor) mAlarmsList.getAdapter().getItem(info.position);
             final SpecialAlarm specialalarm =new SpecialAlarm(c);
             
        	switch (item.getItemId()) {
        	
            case R.id.delete_alarm:
                // Confirm that the alarm will be deleted.
                new AlertDialog.Builder(this)
                        .setTitle(getString(R.string.delete_alarm))
                        .setMessage(getString(R.string.delete_alarm_confirm))
                        .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface d, int w) {
                                    	//点击确定后，将会执行以下操作
                                    	//为什么这个地方选中的Item的ID，会比正常的多1呢？
                                    	int temp = id-count1;
                                        SpecialAlarms.deleteAlarm(AlarmClock.this,temp);
                                        sectionadapter.notifyDataSetChanged();
                                    	initCountDown();
                                    }
                                })
                        .setNegativeButton(android.R.string.cancel, null)
                        .show();
                return true;

            case R.id.enable_alarm:
               
                SpecialAlarms.enableAlarm(this, specialalarm.id, !specialalarm.enabled);
                if (!specialalarm.enabled) {
                    SpecialSetAlarm.popAlarmSetToast(this, specialalarm.hour, specialalarm.minutes);
                }
                return true;

            case R.id.edit_alarm:
                Intent intent = new Intent(this, SpecialSetAlarm.class);
                intent.putExtra(SpecialAlarms.ALARM_ID, id);
                startActivity(intent);
                return true;
                
            case R.id.share_alarm:
            	
                Long temptime= SpecialAlarms.getMillTime(specialalarm);
               // String location = SpecialAlarms.getLocationOfRecord(AlarmClock.this, specialalarm);
             //   iintent.putExtra("Location", location);
                SpecialAlarms.SendColorMessage(AlarmClock.this, temptime, specialalarm.location);
                return true;

            default:
                break;
        }
        return super.onContextItemSelected(item);
        }
       
    }

    
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        mFactory = LayoutInflater.from(this);
        mPrefs = getSharedPreferences(PREFERENCES, 0);
        NormalCursor = Alarms.getAlarmsCursor(getContentResolver());
        SpecialCursor = SpecialAlarms.getAlarmsCursor(getContentResolver());
        //启动服务，监听短信的变化
        Log.v("启动服务");
        Intent intent = new Intent(this, SmsService.class);
        startService(intent);
        findViews();
        initCountDown();

    }
    private void findViews() {
    	
        setContentView(R.layout.alarm_clock);
        mAlarmsList = (ListView) findViewById(R.id.alarms_list);
       // mSpecialAlarmsList = (ListView) findViewById(R.id.specialalarms_list);
         adapter = new AlarmTimeAdapter(this, NormalCursor);
         specialadapter = new SpecialAlarmTimeAdapter(this, SpecialCursor);
        
        sectionadapter.addSection("普通闹钟",adapter);

         sectionadapter.addSection("记事闹钟",specialadapter);

        mAlarmsList.setAdapter(sectionadapter);
        mAlarmsList.setVerticalScrollBarEnabled(true);
        mAlarmsList.setOnItemClickListener(this);
        mAlarmsList.setOnCreateContextMenuListener(this);
        addAlarm = findViewById(R.id.add_alarm);
        addAlarm.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                   
                	showPopupWindow();
                }
            });
        addAlarm.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                public void onFocusChange(View v, boolean hasFocus) {
                    v.setSelected(hasFocus);
                }
        });
    }
    
    /**
     * 进行一些初始化主页倒计时的工作
     */
    public void initCountDown()
    {
        day =(TextView)findViewById(R.id.NumDay);
        
        hour =(TextView)findViewById(R.id.NumHour);
        
        minute =(TextView)findViewById(R.id.Numminute);
        
        Long temp = MyCount.caculateLastTime(this);
        
        MyCount mc = new MyCount(temp,1000*60,day,hour,minute);
       
        mc.start();
    }
    
    SectionedAdapter sectionadapter=new SectionedAdapter() {
    	
		protected View getHeaderView(String caption, int index,View convertView,ViewGroup parent) {
			TextView result=(TextView)convertView;
			
			if (convertView==null) {
				result=(TextView)getLayoutInflater().inflate(R.layout.header, null);
			}
			
			result.setText(caption);
			
			return(result);
		}
	};
    
    
    
    //显示PopupWindow的方法 
	public void showPopupWindow() {

		View popunwindwow = getLayoutInflater().inflate(
				R.layout.popuwindowlayouts, null);
			
		
		NormalButton = popunwindwow.findViewById(R.id.ButtonNormal);
		ButtonSpecial = popunwindwow.findViewById(R.id.ButtonSpecial);
		   //添加一个新的闹钟、
	    //修改计划，转换为录制音频的动作，然后进行保存
	  
        NormalButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(AlarmClock.this,SoundRecorder.class);
		        intent.putExtra("Button", "Normal");
		        //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		        startActivity(intent);
		        
			}
		});
		
        ButtonSpecial.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(AlarmClock.this,SoundRecorder.class);
		        intent.putExtra("Button", "Special");
		    //    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		        startActivity(intent);
			}
		});
      //点击添加一个闹钟，就会弹出一个Popupwindow
		PopupWindow mPopupWindow = new PopupWindow(popunwindwow,
				LayoutParams.FILL_PARENT, LayoutParams. FILL_PARENT,true);
		ColorDrawable cd = new ColorDrawable(-0000);  
		mPopupWindow.setBackgroundDrawable(cd);  
	    //mPopupWindow.showAtLocation(this.findViewById(R.id.alarm_clock), Gravity.RIGHT, 0, 0);
        mPopupWindow.setFocusable(true);
  /**
   * 能够进行Window的界面灰度的调整，但是背景
   * 的调整后就不会再回复，因此不行
   * WindowManager.LayoutParams lp = getWindow().getAttributes();

     lp.alpha = 0.5f; //0.0-1.0

     getWindow().setAttributes(lp);
   */

  /**\
   * 	需要添加这句后，才能使得点击其他区域，popopWindow消失
     因为popupwindow在初始时，会检测background是否为null,如果是空，
     那么onTouch oronKeyevents就不会相应，所以必须设置：
     ColorDrawable cd = new ColorDrawable(-0000);
     mPopupWindow.setBackgroundDrawable(cd);
     而不能是这样：
          mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
     ，
   */

        mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.showAsDropDown(addAlarm);
		
	}

 

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ToastMaster.cancelToast();
        NormalCursor.deactivate();
    }

    @Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		initCountDown();
	}
    @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initCountDown();
	}
	@Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
    	
        getMenuInflater().inflate(R.menu.context_menu, menu);
        tempview = view;
        final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        if(view.getId()==R.id.alarms_list)
        {
        	 final Cursor c = (Cursor) mAlarmsList.getAdapter().getItem((int) info.position);
        	final Alarm alarm = new Alarm(c);
        	 final Calendar cal = Calendar.getInstance();
             cal.set(Calendar.HOUR_OF_DAY, alarm.hour);
             cal.set(Calendar.MINUTE, alarm.minutes);
             final String time = Alarms.formatTime(this, cal);

             final View v = mFactory.inflate(R.layout.context_menu_header, null);
             TextView textView = (TextView) v.findViewById(R.id.header_time);
             textView.setText(time);
             textView = (TextView) v.findViewById(R.id.header_label);
             textView.setText(alarm.label);

             menu.setHeaderView(v);
             if (alarm.enabled) {
                 menu.findItem(R.id.enable_alarm).setTitle(R.string.disable_alarm);
             }
        }
        else
        { 
        	final Cursor c = (Cursor) mSpecialAlarmsList.getAdapter().getItem((int) info.position);
        	final SpecialAlarm alarm = new SpecialAlarm(c);
        	 final Calendar cal = Calendar.getInstance();
             cal.set(Calendar.HOUR_OF_DAY, alarm.hour);
             cal.set(Calendar.MINUTE, alarm.minutes);
             final String time = Alarms.formatTime(this, cal);

             final View v = mFactory.inflate(R.layout.context_menu_header, null);
             TextView textView = (TextView) v.findViewById(R.id.header_time);
             textView.setText(time);
             textView = (TextView) v.findViewById(R.id.header_label);
             textView.setText(alarm.label);

             menu.setHeaderView(v);
             if (alarm.enabled) {
                 menu.findItem(R.id.enable_alarm).setTitle(R.string.disable_alarm);
             }
        }
    }
    


	//点击系统菜单键    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_item_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                return true;
            case R.id.menu_item_desk_clock:
                startActivity(new Intent(this, AlarmClock.class));
                return true;
            case R.id.menu_item_add_alarm:
                //addNewAlarm();
                return true;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	
        getMenuInflater().inflate(R.menu.alarm_list_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
//点击Item后，进入到设置闹钟 
    public void onItemClick(AdapterView parent, View v, int pos, long id) {
    	if(parent.getId()==R.id.alarms_list)
    	{
    		Intent intent = new Intent(this, SetAlarm.class);
            intent.putExtra(Alarms.ALARM_ID, (int) id);
            startActivity(intent);
    	}else
    	{
    		Intent intent = new Intent(this, SpecialSetAlarm.class);
            intent.putExtra(Alarms.ALARM_ID, (int) id);
            startActivity(intent);
    	}
    	
    }


   
    
    
}
